import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'
import router from '../router/index'

const Axios = axios.create({
  baseURL:
    'https://www.easy-mock.com/mock/5b4eabff56c59c6f56266157/testMock/login',
  timeout: 50000,
  responseType: 'json',
  withCredentials: true // 是否允许带cookie这些
  // headers: {
  //   "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
  // }
})

//POST传参序列化(添加请求拦截器)
Axios.interceptors.request.use(
  config => {
    if (
      config.method === 'post' ||
      config.method === 'put' ||
      config.method === 'delete'
    ) {
      // 序列化
      config.data = qs.stringify(config.data)
    }

    // 若是有做鉴权token , 就给头部带上token
    if (localStorage.token) {
      config.headers.Authorization = localStorage.token
    }
    return config
  },
  error => {
    Message({
      showClose: true,
      message: error,
      type: 'error'
    })
    return Promise.reject(error)
  }
)

//返回状态判断(添加响应拦截器)
Axios.interceptors.response.use(
  response => {
    if (res.data && !response.data.success) {
      Message({
        showClose: true,
        message: res.data,
        type: 'error'
      })
      return Promise.reject(response.data)
    }
    return response
  },
  error => {
    if (!window.sessionStorage.getItem('user_token')) {
      router.push({
        path: '/login'
      })
    } else {
      // 根据服务器状态码跳转不同的错误状态页面
      if (error.response.status === 403) {
        router.push({
          path: '/error/403'
        })
      }
      if (error.response.status === 500) {
        router.push({
          path: '/error/500'
        })
      }
      if (error.response.status === 502) {
        router.push({
          path: '/error/502'
        })
      }
      if (error.response.status === 404) {
        router.push({
          path: '/error/404'
        })
      }
    }

    return Promise.reject(error.response.data)
  }
)
// 对axios的实例重新封装成一个plugin ,方便 Vue.use(xxxx)
export default {
  install: function(Vue, Option) {
    Object.defineProperty(Vue.prototype, '$http', { value: Axios })
  }
}
